package com.litchi.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

import com.lib.uil.ToastUtils;
import com.litchi.R;
import com.litchi.activity.FavorActivity.ViewHolder;
import com.litchi.app.MyApplication;
import com.litchi.app.SysApplication;
import com.litchi.bean.Address;
import com.litchi.bean.InCart;
import com.litchi.bean.Order;
import com.litchi.bean.OrderGoods;
import com.litchi.bean.UserBean;
import com.litchi.utils.Constants;
import com.litchi.utils.DBUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ConfirmOrderActivity extends Activity implements OnClickListener {
	private MyApplication mApplication;
	private ArrayList<String> selectedList;
	private ArrayList<String> goodsList;

	private String price;
	private boolean newOrder = true;
	private Context mContext;
	private com.litchi.utils.HorizontialListView mListView;
	private View addressView, payView, backView,addAddressView;
	private TextView priceText, countText;
	private TextView nameText, phoneText, provinceText, addressText;
	private String name, phone, province, addressStr;
	private Handler mHandler;
	private UserBean mUserBean;
	private List<Address> mAddressList;
	private List<OrderGoods> mOrderGoodsList;
	private String orderId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cart_confirm);
		SysApplication.getInstance().addActivity(this);
		initData();
		initView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@SuppressLint("HandlerLeak")
	public void initData() {
		mContext = this;
		mApplication = (MyApplication) mContext.getApplicationContext();
		mOrderGoodsList = new ArrayList<OrderGoods>();
		selectedList = new ArrayList<String>();
		goodsList = new ArrayList<String>();
		selectedList = getIntent().getStringArrayListExtra(
				Constants.CART_CONFIRM_KEY);
		goodsList = getIntent().getStringArrayListExtra(
				Constants.CART_CONFIRM_GOODS_KEY);
		orderId = getIntent().getStringExtra(Constants.ORDER_ID);
		price = getIntent().getStringExtra(Constants.CART_PRICE_KEY);
		newOrder = getIntent().getBooleanExtra(Constants.NEW_ORDER, true);
		mHandler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(android.os.Message msg) {

				mAddressList = (List<Address>) msg.obj;

				if (mAddressList.size() > 0) {
					name = mAddressList.get(0).getName();
					phone = mAddressList.get(0).getPhone();
					province = mAddressList.get(0).getProvince();
					addressStr = mAddressList.get(0).getAddress();

					if (null != nameText && null != phoneText
							&& null != provinceText && null != addressText) {
						nameText.setText(name);
						phoneText.setText(phone);
						provinceText.setText(province);
						addressText.setText(addressStr);
					}
				}

			}

		};

		mUserBean = BmobUser.getCurrentUser(this, UserBean.class);

		if (null != mUserBean.getObjectId()) {

			BmobQuery<Address> query = new BmobQuery<Address>("Address");
			query.addWhereEqualTo("userId", mUserBean.getObjectId());
			query.findObjects(mContext, new FindListener<Address>() {

				@Override
				public void onSuccess(List<Address> arg0) {
					// TODO Auto-generated method stub
					// list = arg0;
					Message msg = new Message();
					msg.obj = arg0;
					mHandler.sendMessage(msg);
				}

				@Override
				public void onError(int arg0, String arg1) {
					// TODO Auto-generated method stub
					ToastUtils.showToast(mContext, arg0 + arg1);
				}
			});

		}

	}

	public void initView() {
		addAddressView=findViewById(R.id.add_address);
		addAddressView.setOnClickListener(this);
		mListView = (com.litchi.utils.HorizontialListView) findViewById(R.id.list_cart_confirm);
		priceText = (TextView) findViewById(R.id.text_confirm_price);
		countText = (TextView) findViewById(R.id.text_confirm_count);
		backView = findViewById(R.id.img_back);
		backView.setOnClickListener(this);
		addressView = findViewById(R.id.confirm_address);
		addressView.setOnClickListener(this);
		payView = findViewById(R.id.confirm_btn_pay);
		payView.setOnClickListener(this);
		nameText = (TextView) findViewById(R.id.text_address_name);
		phoneText = (TextView) findViewById(R.id.text_address_phone);
		provinceText = (TextView) findViewById(R.id.text_address_province);
		addressText = (TextView) findViewById(R.id.text_address);

		if (null != price) {
			priceText.setText(price);
		}

		if (null != selectedList && selectedList.size() > 0) {
			countText.setText("共" + selectedList.size() + "种商品");
			mListView.setAdapter(new MyAdapter());
		}
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return selectedList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return selectedList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@SuppressWarnings("null")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder mViewHolder;
			if (null == convertView) {
				mViewHolder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_confirm_cart, null);
				mViewHolder.goodsImg = (ImageView) convertView
						.findViewById(R.id.img_goods_icon);

			} else {
				mViewHolder = (ViewHolder) convertView.getTag();
			}

			mApplication.imgLoader.displayImage(Constants.HTTP_FILE
					+ selectedList.get(position), mViewHolder.goodsImg);
			convertView.setTag(mViewHolder);
			return convertView;
		}

		class ViewHolder {
			ImageView goodsImg;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.confirm_address:
			confirmAddress();
			break;
		case R.id.confirm_btn_pay:
			if (!addAddressView.isShown()) {
				toPay();
			}else {
				ToastUtils.showToast(mContext, "请先选择收货地址...");
			}
			
			break;
		case R.id.img_back:
			finish();
			break;
		case R.id.add_address:
			confirmAddress();
			break;
		default:
			break;
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case RESULT_OK:
			addAddressView.setVisibility(View.GONE);
			addressView.setVisibility(View.VISIBLE);
			Address address = (Address) data
					.getSerializableExtra(Constants.ADDRESS_KEY);

			name=address.getName();
			phone=address.getPhone();
			province=address.getProvince();
			addressStr=address.getAddress();
			nameText.setText(name);
			phoneText.setText(phone);
			provinceText.setText(province);
			addressText.setText(addressStr);

			break;
		default:
			break;
		}
	}

	public void confirmAddress() {
		Intent intent = new Intent(mContext, OrderAddressActivity.class);
		intent.putExtra(Constants.USER_KEY, mUserBean.getObjectId());
		startActivityForResult(intent, Constants.REQUEST_ORDER_ADDRESS_CODE);
	}

	public void toPay() {
		if (newOrder) {

			orderId = "" + new Date().getTime();
			final Order mOrder = new Order();
			mOrder.setOrderId("" + orderId);
			mOrder.setUserId(mUserBean.getObjectId());
			mOrder.setAddressName(name);
			mOrder.setAddressPhone(phone);
			mOrder.setAddress(province + addressStr);
			mOrder.setPrice(price);
			mOrder.setStatus(Constants.ORDER_STATUS_UNPAID_KEY);
			mOrder.setTableName("Order");

			mOrder.save(mContext, new SaveListener() {

				@Override
				public void onSuccess() {
					// TODO Auto-generated method stub

				}

				@Override
				public void onFailure(int arg0, String arg1) {
					// TODO Auto-generated method stub
					ToastUtils.showToast(mContext, "清单提交失败" + arg1);

				}
			});

		}
		if (goodsList.size() > 0) {

			for (int i = 0; i < goodsList.size(); i++) {
				OrderGoods mGoods = new OrderGoods();
				// cart.getGoodsId()+"-"+cart.getGoodsName()+"-"+cart.getGoodsIcon()+"-"+cart.getGoodsPrice()+"-"+cart.getNum()
				String[] msg = goodsList.get(i).split(":");

				mGoods.setGoodsId(msg[0]);
				mGoods.setGoodsName(msg[1]);
				mGoods.setGoodsImg(msg[2]);
				mGoods.setGoodsPrice(msg[3]);
				mGoods.setGoodsCount(msg[4]);
				mGoods.setTableName("OrderGoods");
				mGoods.setOrderId(orderId);
				if (newOrder) {
					mGoods.save(mContext);
				}

				mOrderGoodsList.add(mGoods);
			}

		}

		new DeleteCartGoodsTask(mOrderGoodsList, "" + orderId).execute();
	}

	class DeleteCartGoodsTask extends AsyncTask<Void, Void, Boolean> {

		private List<OrderGoods> mGoods;
		private String orderId;

		public DeleteCartGoodsTask(List<OrderGoods> mGoods, String orderId) {
			this.mGoods = mGoods;
			this.orderId = orderId;
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			if (mGoods.size() > 0) {
				List<InCart> cart = DBUtils.getInCart();
				for (int i = 0; i < cart.size(); i++) {
					InCart c = cart.get(i);
					for (OrderGoods mOrderGoods : mGoods) {
						if (c.getGoodsId().equals(mOrderGoods.getGoodsId())) {
							DBUtils.deleteCart(c);
						}
					}

				}
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result) {
				
				// 通知主页刷新购物车商品数
				Intent intentCart = new Intent();
				intentCart.setAction(Constants.BROADCAST_FILTER.FILTER_CODE);
				intentCart.putExtra(Constants.BROADCAST_FILTER.EXTRA_CODE, Constants.INTENT_KEY.REFRESH_INCART);
				sendBroadcast(intentCart);
				
				
				Intent intent = new Intent(mContext, CashierActivity.class);
				intent.putExtra(Constants.ORDER_PRICE_KEY, price);
				intent.putExtra(Constants.ORDER_ID_KEY, orderId);
				startActivity(intent);
			}
		}
	}

}
